<template>
	<view class="volunteerProfile">
		<view :class="item.type == 'upload_img' || item.type == 'upload_imgs' || item.type == 'upload_img_cat' ? 'photo' : (item.type == 'textarea' ? 'speciality' : (item.type == 'radio' || item.type == 'checkbox' ? 'downItem' : '') + ' line')" v-for="(item, index) in info" :key="index">
			<view><span class='required' v-if="item.rules.isRequired == 1">*</span>{{item.name}}</view>
			<view :class="item.type == 'upload_img' || item.type == 'upload_imgs' || item.type == 'upload_img_cat' ? 'list' : 'right' ">
				<picker v-if="item.type == 'select'" @change="bindPickerChange" :value="item.showVal" :range="item.valList" range-key="itemName" :data-current="item.valField" :data-key="index" :disabled="item.rules.isEdit == 0">
					<view class="item">{{item.nowValName}}</view>
				</picker>
				<input v-if="item.type == 'input'" type="text" v-model="formData.valItem[item.valField]"  placeholder-style="color:rgba(153,153,153,0.9);" :placeholder="item.nowValName" :disabled="item.rules.isEdit == 0"/>
				<picker v-if="item.type == 'date'" mode="date" :value="item.showVal" :start="startDate" :end="endDate" @change="bindDateChange" :data-current="item.valField" :data-key="index" :disabled="item.rules.isEdit == 0">
					<view class="item">{{item.nowValName}}</view>
				</picker>
				<view v-if="item.type == 'select' || item.type == 'date'" class="jt"></view>
				<view v-if="item.type == 'upload_img' || item.type == 'upload_img_cat'" style="position: relative;">
					<image :src="item.imgUrl ? item.imgUrl : 'http://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png'" mode="aspectFill" 
						@click="chooseImage(index)">
					</image>
					<image @click="delImg(index)" v-if="item.rules.isEdit == 1 && item.imgUrl" src="http://hdsq.aoorange.cn/attachment/xcx/icon/del-new.png" class="del" mode="aspectFill"></image>
				</view>
				<view class="photos" v-if="item.type == 'upload_imgs'">
					<view class="photo_list" v-for="(item2,index2) in item.imgList" :key="index2">
					   <image :src="item2.imgUrl" mode="aspectFill"></image>
					   <image v-if="item.rules.isEdit == 1" @click="delImg(index, index2)" src="http://hdsq.aoorange.cn/attachment/xcx/icon/del-new.png" class="del" mode="aspectFill"></image>
					</view>
					<image src="http://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png" mode="aspectFill" @click="chooseImage(index)"></image>
				</view>
			</view>
			<div v-if="(item.type == 'checkbox' || item.type == 'radio') " class="A" v-for="(optionItem,index2) in item.valList" :key="index2">
			  <p @click="selAnswerFun(item.type, index, optionItem.itemId)">
			    <i :class="(isCheck(item.type, index, optionItem.itemId) ? 'check ' : '') + item.type"></i>
			    <span>{{optionItem.itemName}}</span>
			  </p>
			</div>
			<textarea v-if="item.type == 'textarea'" v-model="formData.valItem[item.valField]" :placeholder="item.nowValName" :disabled="item.rules.isEdit == 0"/>
		</view>
		<view class="bottom" @click="subForm()" >确认提交</view>
	<kps-image-cutter @ok="onok" @cancel="oncancle" :url="url" positionItem="fixed" fixed="true" :blob="false"  :maxWidth="100" :maxHeight="100"></kps-image-cutter>
	</view>
</template>

<script>
	import serve from '../static/request.js';
	import storage from '../static/appkey.js';
	import common from '../static/jump.js';
	import kpsImageCutter from "@/components/ksp-image-cutter/ksp-image-cutter.vue";
	export default {
		data() {
			return {
				info: {},
				joinInfo: {},
				formInput: [],
				redioList: [],
				checkboxList: [[]],
				formData:{
					appkey: uni.getStorageSync('appkey'),
					'access-token': uni.getStorageSync('access-token'),
					id : 0,
					valItem: {},
				},
				url: "",
				dataId: 0,
				disabledName: '未填写',
			}
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		components: {
			kpsImageCutter
		},
		methods: {
			getInfo() {
				serve
					.request({
						url: '/spread/business/upload',
						data: {
							appkey: uni.getStorageSync('appkey'),
							'access-token': uni.getStorageSync('access-token'),
							id: this.formData.id
						}
					})
					.then(res => {
						this.info = res.data;
						this.info.forEach((item, key) => {
							this.$set(this.formData.valItem, item.valField, item.nowVal);
							if((item.type == 'select')) {
								if(item.nowVal > 0){
									item.valList.forEach((valItem, valKey) => {
										if(valItem.itemId == item.nowVal) {
											this.$set(this.info[key], 'showVal', valKey);
										}
									});
								} else {
									this.$set(this.info[key], 'showVal', '');
								}
							} else if(item.type == 'radio') {
								this.redioList[key] = item.nowVal;
							} else if(item.type == 'checkbox') {
								this.checkboxList[key] = [];
								let selCheck = item.nowVal ? item.nowVal.split(";") : [];
								item.valList.forEach((optionItem, key2) => {
									this.checkboxList[key][optionItem.itemId] = selCheck.indexOf(optionItem.itemId) === -1 ? false : true;
								});
							}
						});
						console.info(this.info);
					});
			},
			isCheck(type, index, index2) {
				if(type == 'radio') {
					return this.redioList[index] == index2;
				} else if(type == 'checkbox') {
					return this.checkboxList[index][index2];
				}
				return false;
			},
			selAnswerFun(type, k, k1) {
				// console.info(type + ' == ' + k + ' == ' + k1);
				if(type == 'radio') {
					this.redioList[k] = k1;
				} else {
					this.checkboxList[k][k1] = !this.checkboxList[k][k1];
				}
				this.$forceUpdate();
			},
			bindPickerChange:function(e) {
				let key = e.target.dataset.key;
				let curindex = e.target.dataset.current;
				let value =  e.target.value;
				let valList = this.info[key].valList;
				
				for(let k in valList) {
					if(k == value) {
						this.$set(this.formData.valItem, curindex, valList[k].itemId);
						this.info[key].nowValName = valList[k].itemName;
						return ;
					}
				}
				// this.$set(this.formData, curindex, value);
				// this.$set(this.info[key], 'nowVal', value);
				// this.info[key].nowValName = this.info[key].valList[this.info[key].nowVal].itemName;
				this.$forceUpdate();
				// console.info(curindex + ' === ' + value);
			},
			bindDateChange: function(e) {
				let dateVal = e.target.value;
				let key = e.target.dataset.key;
				let item = this.info[key];
				this.$set(this.formData.valItem, item.valField, dateVal);
				this.info[key].nowValName = dateVal;
				this.$forceUpdate();
			},
			chooseImage(key){
				var self = this;
				let item = self.info[key];
				if (item.type == 'upload_imgs' && item.imgList.length >= item.rules.num) {
					return ;
				}
				if(item.rules.isEdit == 0) {
					return ;
				}
				uni.chooseImage({
					sizeType: ['compressed'],
					success: (res) => {
						if(item.type == 'upload_img_cat') {
							self.url = res.tempFilePaths[0];
							self.dataId = key;
							self.$forceUpdate();
						} else if (item.type == 'upload_img') {
							uni.showLoading({
								title: '上传中···',
								mask: true
							});
							self.uploadImg(key, res.tempFilePaths[0]);
						} else if (item.type == 'upload_imgs'){
							const tempFilePaths = res.tempFilePaths;
							if((Number(tempFilePaths.length) + Number(item.imgList.length)) > item.rules.num) {
								uni.showToast({
									title: "最多能上传"+item.rules.num+"张，还能上传"+(Number(item.rules.num) - Number(item.imgList.length))+"张",
									icon: 'none',
								});
								return ;
							}
							uni.showLoading({
								title: '上传中···',
								mask: true
							});
							tempFilePaths.forEach((imgPath, k) => {
								// console.info(imgPath);
								this.uploadImg(key, imgPath);
							});
						}
					}
				});
			},
			onok(ev) {
				uni.showLoading({
				    title: '上传中···',
					mask: true
				});
				var self = this;
				let item = self.info[self.dataId];
				uni.uploadFile({
						url: serve.apiUrl() + '/v1/file/images?appkey=' + uni.getStorageSync('appkey'),
						filePath: ev.path,
						name: 'file',
						formData: {
							'access-token': uni.getStorageSync('access-token'),
						},
						success: (uploadFileRes) => {
							let result = JSON.parse(uploadFileRes.data);
							if (result.code == 200) {
								self.$set(self.formData.valItem, item.valField, result.data.imgPath);
								self.info[self.dataId].imgUrl = result.data.imgUrl;
								self.dataId = 0;
								self.url = '';
								self.$forceUpdate();
							} else {
								uni.showToast({
									title: result.message,
									icon: 'none',
								})
							}
							uni.hideLoading();
						}
					});
			},
			oncancle() {
				this.url = '';
				this.dataId = 0;
				this.$forceUpdate();
			},
			uploadImg(key, imgPath) {
				var self = this;
				let item = self.info[key];
				uni.uploadFile({
					url: serve.apiUrl()+'/v1/file/images?appkey='+ uni.getStorageSync('appkey'), 
					filePath: imgPath,
					name: 'file',
					formData: {
						'access-token': uni.getStorageSync('access-token'),
					},
					success: (uploadFileRes) => {
						let result = JSON.parse(uploadFileRes.data);
						if(result.code == 200) {
							if(item.type == 'upload_img'){
								self.$set(self.formData.valItem, item.valField, result.data.imgPath);
								self.info[key].imgUrl = result.data.imgUrl;
							} else {
								let imgArr = [{}];
								self.$set(imgArr[0], 'imgUrl', result.data.imgUrl);
								self.$set(imgArr[0], 'imgPath', result.data.imgPath);
								self.info[key].imgList = self.info[key].imgList.concat(imgArr);
							}
							self.$forceUpdate();
						} else {
							uni.showToast({
								title: result.message,
								icon: 'none',
							})
						}
						uni.hideLoading();
					}
				});
			},
			delImg(key, key2) {
				var self = this;
				let item = self.info[key];
				if(item.type == 'upload_imgs'){
					self.info[key].imgList.splice(key2,1);
				} else {
					self.info[key].imgUrl = '';
					self.info[key].nowVal = '';
					this.formData.valItem[item.valField] = '';
				}
				self.$forceUpdate();
			},
			subForm() {
				let isSub = true;
				this.info.forEach((item, index) => {
					if(item.type == 'upload_imgs') {
						var imgPath = ''
						item.imgList.forEach((item, index) => {
							imgPath += (index > 0 ? ";" : "") + item.imgPath;
						});
						// this.$set(this.formData.valItem, item.valField, result.data.imgPath);
						this.formData.valItem[item.valField] = imgPath;
					} else if (item.type == 'radio') {
						this.formData.valItem[item.valField] = this.redioList[index];
					} else if(item.type == 'checkbox') {
						let checkboxAnswer = '';
						let is_check = false;
						item.valList.forEach((optionItem, key2) => {
							if(this.checkboxList[index][optionItem.itemId]) {
								checkboxAnswer += (is_check ? ';' : '') + optionItem.itemId;
								is_check = true;
							}
						});
						console.info(checkboxAnswer);
						this.formData.valItem[item.valField] = checkboxAnswer;
					}
					if(item.rules.isRequired == 1 && this.formData.valItem[item.valField] == "") {
						uni.showToast({
							title: item.name + "不能为空",
							icon: 'none',
						});
						isSub = false;
						return ;
					}
				});
				if(!isSub) {
					return ;
				}
				// this.formData.valItem = JSON.stringify(this.formData.valItem);
				// console.info(this.formData);
				var self = this;
				serve
					.request({
						url: '/spread/business/edit',
						data: self.formData
					})
					.then(res => {
						self.$forceUpdate();
						let code = res.code;
						uni.showModal({
						    title: '提示',
						    content: res.message,
							showCancel: false,
							success: function(res) {
								if (res.confirm && code == 200) {
									uni.navigateBack({
									    delta: 1
									});
									// console.info(code);
									// uni.redirectTo({
									// 	url: '/pages/business/info?id='+self.formData.id
									// });
									// common.jump('business_info', self.formData.id);
								}
							}
						});
						return ;
						// uni.showToast({
						// 	title: res.message,
						// 	icon: 'none',
						// });
						// if(res.code == 200) {
						// 	common.jump('my');
						// }
					});
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
			
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			}
		},
		onLoad(options) {
			this.formData.id = options.id || 0;
			if(this.formData.id == 0) {
				uni.showToast({
					title: "错误的访问方式",
					icon: 'none',
					success() {
						setTimeout(function () {
							common.jump('business_index')
						}, 2000) 
					}
				});
				return ;
			}
			this.getInfo();
		},
	}
</script>

<style scoped lang="scss">
	.volunteerProfile{
		padding-bottom: 100rpx;
		.bottom {
			width: 100%;
			height: 100rpx;
			line-height: 100rpx;
			text-align: center;
			font-size: 32rpx;
			color: rgba(255, 255, 255, 1);
			background: rgba(251, 202, 63, 1);
			bottom: 0rpx;
			position: fixed;
			z-index: 999;
		}
		.speciality{
			padding: 42rpx 30rpx 25rpx;
			box-sizing: border-box;
			textarea{
				padding: 33rpx 38rpx;
				background:rgba(232,232,232,0.2);
				border-radius:12px;
				font-size:32rpx;
				// color:rgba(66,81,114,0.2);
				height:240rpx;
			}
		}
		.photo{
			padding: 44rpx 30rpx;
			box-sizing: border-box;
			border-bottom: 1rpx rgba(235,235,235,1) solid;
			position: relative;

			.title{
				font-size:32rpx;
				color:rgba(153,153,153,1);
			}
			.list{
				display: flex;
				flex-wrap: wrap;
				image{
					margin-top: 40rpx;
					margin-right: 20rpx;
					width:200rpx;
					height:200rpx;
				}
				.del{
					width: 48rpx !important;
					position: absolute;
					height: 48rpx !important;
					top: -24rpx;
					right: -24rpx;
				}
				.photos{
					box-sizing: border-box;
					padding: 30rpx 30rpx;
					display: flex;
					flex-wrap: wrap;
					image{
						width:200rpx;
						height:200rpx;
						border-radius:10rpx;
						margin-bottom: 20rpx;
					}
					.photo_list{
						margin-right: 30rpx;
						padding-bottom: 20rpx;
						display: flex;
						flex-direction: column;
						align-items: flex-end;
						position: relative;
						view{
							color: red;
							font-size: 30rpx;
						}
						.del{
							width: 48rpx !important;
							position: absolute;
							height: 48rpx !important;
							top: -24rpx;
							right: -24rpx;
						}
					}
				}
			}
		}
		.downItem{
			height: 100% !important;
			display: list-item !important;
			line-height: 80rpx !important;
		}
		.required{
			color: #f00;
		}
		
		.line {
				height: 130rpx;
				box-sizing: border-box;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0rpx 30rpx;
				color:rgba(153,153,153,0.9);
				font-size: 32rpx;
				border-bottom: 1rpx rgba(235,235,235,1) solid;
				
				.right {
					position: relative;
					height: 100%;
					display: flex;
					align-items: center;
		
					.item {
						margin-right: 30rpx;
					}
					input{
						text-align: right;
					}
		
					.jt {
						position: absolute;
						right: 0rpx;
						top: 62rpx;
						content: '';
						border: 1rpx solid rgba(57, 72, 107, 0.5);
						border-width: 0 3rpx 3rpx 0;
						padding: 6rpx;
						transform: rotate(-45deg);
						-webkit-transform: rotate(-45deg);
					}
				}
				.A {
					height: 70rpx;
					box-sizing: border-box;
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 0rpx 30rpx;
					color:rgba(153,153,153,0.9);
					font-size: 32rpx;
					
					p {
						display: flex;
						align-items: center;
						line-height: 48rpx;
						font-size: 32rpx;
						color: rgba(60, 72, 104, 1);
						margin-bottom: 35rpx;
				
						.radio {
							display: block;
							width: 48rpx;
							height: 48rpx;
							border: 1px solid rgba(57, 72, 107, 1);
							border-radius: 50%;
							box-sizing: border-box;
							margin-right: 10rpx;
						}
					   .checkbox {
							width: 40rpx;
							height: 40rpx;
							line-height: 60rpx;
							text-align: center;
							margin: 0 10rpx;
							border: 2rpx solid #888;
							color: #999;
							font-size: 28rpx;  
						}
						.radio.check {
							border: none;
							background: url(http://hdsq.aoorange.cn/attachment/xcx/my/check.png);
							background-size: 100% auto;
						}
						.checkbox.check {
							border: none;
							background: url(http://hdsq.aoorange.cn/attachment/xcx/my/checkbox_check.png);
							background-size: 100% auto;
						}
					}
				}
			}
	}
</style>
